package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.service.BusinessService;
import cn.edu.tju.core.security.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/businesses")
@Tag(name="管理店铺", description = "提供对店铺的增删改查功能")
public class BusinessController {
    @Autowired
    private UserService userService;

    @Autowired
    BusinessService businessService;

    @GetMapping("")
    @Operation(summary = "获取所有店铺", description = "获取所有店铺列表")
    public HttpResult<List<Business>> getBusinesses(){
        List<Business> businesses = businessService.findAll();
        return HttpResult.success(businesses);
    }

    @PostMapping("")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "新增店铺", description = "创建一个新的店铺（需要管理员权限）")
    public HttpResult<Business> addBusiness(@RequestBody Business business){
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            // 检查是否是管理员
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(authority -> "ADMIN".equals(authority.getName()));

            if(!isAdmin) {
                return HttpResult.failure(ResultCodeEnum.FORBIDDEN, "需要管理员权限");
            }

            // 处理businessOwner设置
            if (business.getBusinessOwner() == null) {
                // 如果有applicantId，使用申请人作为owner
                if (business.getApplicantId() != null) {
                    User applicant = userService.getUserById(business.getApplicantId());
                    if (applicant != null) {
                        business.setBusinessOwner(applicant);
                    } else {
                        // 申请人不存在，使用当前管理员
                        business.setBusinessOwner(currentUser);
                    }
                } else {
                    // 没有指定申请人，使用当前管理员作为owner
                    business.setBusinessOwner(currentUser);
                }
            }

            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            business.setCreateTime(now);
            business.setUpdateTime(now);

            // 设置创建者和更新者
            business.setCreator(currentUser.getId());
            business.setUpdater(currentUser.getId());

            // 设置删除状态
            business.setDeleted(false);

            // 保存店铺
            Business savedBusiness = businessService.save(business);
            return HttpResult.success(savedBusiness);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "创建店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取店铺", description = "根据ID获取店铺的详细信息")
    public HttpResult<Business> getBusiness(@PathVariable("id") Long id){
        Optional<Business> businessOptional = businessService.findById(id);

        if (businessOptional.isPresent()) {
            return HttpResult.success(businessOptional.get());
        } else {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND);
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新店铺", description = "商家更新自己的店铺信息，管理员可以更新所有店铺")
    public HttpResult<Business> updateBusiness(@PathVariable("id") Long id, @RequestBody Business business){
        try {
            // 检查店铺是否存在
            Optional<Business> existingBusinessOptional = businessService.findById(id);
            if (!existingBusinessOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
            }

            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            Business existingBusiness = existingBusinessOptional.get();

            // 权限检查：商家只能修改自己的店铺，管理员可以修改所有店铺
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(auth -> "ADMIN".equals(auth.getName()));
            boolean isOwner = existingBusiness.getBusinessOwner().getId().equals(currentUser.getId());

            if (!isAdmin && !isOwner) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "无权修改此店铺");
            }

            // 如果是商家（非管理员），不允许修改店铺所有者
            if (!isAdmin && business.getBusinessOwner() != null
                    && !business.getBusinessOwner().getId().equals(existingBusiness.getBusinessOwner().getId())) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "商家不能修改店铺所有者");
            }

            // 更新字段
            existingBusiness.setBusinessName(business.getBusinessName());
            // 只有管理员可以修改店铺所有者
            if (isAdmin && business.getBusinessOwner() != null) {
                existingBusiness.setBusinessOwner(business.getBusinessOwner());
            }
            existingBusiness.setBusinessAddress(business.getBusinessAddress());
            existingBusiness.setBusinessExplain(business.getBusinessExplain());
            existingBusiness.setBusinessImg(business.getBusinessImg());
            existingBusiness.setOrderTypeId(business.getOrderTypeId());
            existingBusiness.setStartPrice(business.getStartPrice());
            existingBusiness.setDeliveryPrice(business.getDeliveryPrice());
            existingBusiness.setRemarks(business.getRemarks());

            // 设置更新时间
            existingBusiness.setUpdateTime(LocalDateTime.now());
            existingBusiness.setUpdater(currentUser.getId());

            // 保存更新
            Business updatedBusiness = businessService.save(existingBusiness);
            return HttpResult.success(updatedBusiness);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }

    @PatchMapping("/{id}")
    @Operation(summary = "部分更新店铺", description = "商家部分更新自己的店铺信息，管理员可以部分更新所有店铺")
    public HttpResult<Business> patchBusiness(@PathVariable("id") Long id, @RequestBody Business business){
        try {
            // 检查店铺是否存在
            Optional<Business> existingBusinessOptional = businessService.findById(id);
            if (!existingBusinessOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
            }

            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            Business existingBusiness = existingBusinessOptional.get();

            // 权限检查：商家只能修改自己的店铺，管理员可以修改所有店铺
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(auth -> "ADMIN".equals(auth.getName()));
            boolean isOwner = existingBusiness.getBusinessOwner().getId().equals(currentUser.getId());

            if (!isAdmin && !isOwner) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "无权修改此店铺");
            }

            // 部分更新字段（只更新非null字段）
            if (business.getBusinessName() != null) {
                existingBusiness.setBusinessName(business.getBusinessName());
            }

            // 只有管理员可以修改店铺所有者
            if (business.getBusinessOwner() != null) {
                if (isAdmin) {
                    existingBusiness.setBusinessOwner(business.getBusinessOwner());
                } else if (!business.getBusinessOwner().getId().equals(existingBusiness.getBusinessOwner().getId())) {
                    return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "商家不能修改店铺所有者");
                }
            }

            if (business.getBusinessAddress() != null) {
                existingBusiness.setBusinessAddress(business.getBusinessAddress());
            }
            if (business.getBusinessExplain() != null) {
                existingBusiness.setBusinessExplain(business.getBusinessExplain());
            }
            if (business.getBusinessImg() != null) {
                existingBusiness.setBusinessImg(business.getBusinessImg());
            }
            if (business.getOrderTypeId() != null) {
                existingBusiness.setOrderTypeId(business.getOrderTypeId());
            }
            if (business.getStartPrice() != null) {
                existingBusiness.setStartPrice(business.getStartPrice());
            }
            if (business.getDeliveryPrice() != null) {
                existingBusiness.setDeliveryPrice(business.getDeliveryPrice());
            }
            if (business.getRemarks() != null) {
                existingBusiness.setRemarks(business.getRemarks());
            }

            // 设置更新时间
            existingBusiness.setUpdateTime(LocalDateTime.now());
            existingBusiness.setUpdater(currentUser.getId());

            // 保存更新
            Business updatedBusiness = businessService.save(existingBusiness);
            return HttpResult.success(updatedBusiness);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除店铺", description = "商家删除自己的店铺，管理员可以删除所有店铺")
    public HttpResult<String> deleteBusiness(@PathVariable("id") Long id){
        try {
            // 检查店铺是否存在
            Optional<Business> businessOptional = businessService.findById(id);
            if (!businessOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
            }

            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            Business business = businessOptional.get();

            // 权限检查：商家只能删除自己的店铺，管理员可以删除所有店铺
            boolean isAdmin = currentUser.getAuthorities().stream()
                    .anyMatch(auth -> "ADMIN".equals(auth.getName()));
            boolean isOwner = business.getBusinessOwner().getId().equals(currentUser.getId());

            if (!isAdmin && !isOwner) {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED_OPERATION, "无权删除此店铺");
            }

            // 删除店铺
            businessService.deleteById(id);
            return HttpResult.success("店铺删除成功");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }
}